package com.anrongtec.zcpt.manager;

import android.app.IntentService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;

import com.anrongtec.zcpt.constant.Constant;
import com.anrongtec.zcpt.interfaces.HttpUtil;
import com.anrongtec.zcpt.interfaces.URLConstants;
import com.anrongtec.zcpt.interfaces.module.JsonDataRestult;
import com.anrongtec.zcpt.module.AppModel;
import com.anrongtec.zcpt.util.GsonUtil;
import com.anrongtec.zcpt.util.Util;
import com.art.base.db.LiteOrmDBUtil;
import com.art.base.util.log.LogUtil;
import com.google.gson.reflect.TypeToken;
import com.lzy.okhttputils.callback.StringCallback;

import okhttp3.Request;
import okhttp3.Response;

/**
 * app状态监听
 *
 * @author dongtianhao
 */
public class AppStateManager {
    private static final String TAG = "AppStateManager";
    private static final String ACTION_PKGNAME = "pkgName";
    // app安装卸载事件
    public static final String TYPE_INSTALL = "install";
    public static final String TYPE_UNINSTALL = "uninstall";
    private Context mContext;
    private AppStateBroadcastReceiver appStateReceiver;
    private AppStateListener appStateListener;
    private String type;// 用于上传类型 卸载/安装
    private boolean isUpload;

    public AppStateManager(Context context) {
        mContext = context;
        appStateReceiver = new AppStateBroadcastReceiver();
    }

    /**
     * app状态监听
     */
    private class AppStateBroadcastReceiver extends BroadcastReceiver {
        private String action = null;
        String packageName = "";

        @Override
        public void onReceive(Context context, Intent intent) {
            action = intent.getAction();
            packageName = intent.getData().getSchemeSpecificPart();
            Log.e("卸载报名", packageName);

            switch (action) {
                case Intent.ACTION_PACKAGE_ADDED:// app添加
                    appStateListener.onAppInstalled(packageName);
                    type = TYPE_INSTALL;
                    if (isUpload) {
                        Intent i = new Intent(mContext, UpLoadService.class);
                        i.putExtra(ACTION_PKGNAME, packageName);
                        i.putExtra(Constant.TYPE, type);
                        context.startService(i);
                    }
                    // 安装、卸载完成之后从数据库移除更新的信息
                    LiteOrmDBUtil.update(AppModel.class, "appPackName", packageName, "isNeedUpgrade", "false");
                    break;
                case Intent.ACTION_PACKAGE_REMOVED:// app卸载
                    appStateListener.onAppUninstalled(packageName);
                    type = TYPE_UNINSTALL;
                    if (isUpload) {
                        Intent i = new Intent(mContext, UpLoadService.class);
                        i.putExtra(ACTION_PKGNAME, packageName);
                        i.putExtra(Constant.TYPE, type);
                        context.startService(i);
                    }
//                    List<AppModel> appPackName = LiteOrmDBUtil.getQueryByWhere(AppModel.class, "appPackName", new String[]{packageName});
//                    if (appPackName != null) {
                        // 安装、卸载完成之后从数据库移除更新的信息
                        LiteOrmDBUtil.update(AppModel.class, "appPackName", packageName, "isNeedUpgrade", "false");
//                    }
                    break;
                case Intent.ACTION_PACKAGE_REPLACED://app替换/升级
                    appStateListener.onAppRelpaced(packageName);
                    type = TYPE_INSTALL;
                    if (isUpload) {
                        Intent i = new Intent(mContext, UpLoadService.class);
                        i.putExtra(ACTION_PKGNAME, packageName);
                        i.putExtra(Constant.TYPE, type);
                        context.startService(i);
                    }
                    // 安装、卸载完成之后从数据库移除更新的信息
                    LiteOrmDBUtil.update(AppModel.class, "appPackName", packageName, "isNeedUpgrade", "false");
                    break;
            }
//			if (Intent.ACTION_PACKAGE_ADDED.equals(action)) { // app添加
//				appStateListener.onAppInstalled(packageName);
//				type = TYPE_INSTALL;
//			} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) { // app卸载
//				appStateListener.onAppUninstalled(packageName);
//				type = TYPE_UNINSTALL;
//			} else if (Intent.ACTION_PACKAGE_REPLACED.equals(action)) { // app替换/升级
//				appStateListener.onAppRelpaced(packageName);
//				type = TYPE_INSTALL;
//			}
//
//			// 安装、卸载完成之后从数据库移除更新的信息
//				LiteOrmDBUtil.update(AppModel.class, "appPackName", packageName, "isNeedUpgrade", "false");
        }
    }

    /**
     * 开始监听应用安装情况，不上传
     *
     * @param listener
     */
    public void begin(AppStateListener listener) {
        appStateListener = listener;
        this.isUpload = false;
        registerListener();
    }

    /**
     * 开始监听应用安装情况
     *
     * @param listener 监听app状态
     * @param isUpload 是否上传，默认不上传
     */
    public void begin(AppStateListener listener, boolean isUpload) {
        appStateListener = listener;
        this.isUpload = isUpload;
        registerListener();
    }

    /**
     * ֹͣ反注册监听
     */
    public void unregisterListener() {
        if (appStateListener != null) {
            appStateListener = null;
        }
        if (appStateReceiver != null) {
            mContext.unregisterReceiver(appStateReceiver);
        }
    }

    /**
     * 注册app状态信息广播
     */
    private void registerListener() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_PACKAGE_ADDED);// 成功的安装APK之后
        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);// APP卸载成功之后
        filter.addAction(Intent.ACTION_PACKAGE_REPLACED);// APP替换/升级成功之后
        filter.addDataScheme("package");
        mContext.registerReceiver(appStateReceiver, filter);
    }

    public interface AppStateListener {

        public void onAppInstalled(String pkgName);

        public void onAppUninstalled(String pkgName);

        public void onAppRelpaced(String pkgName);
    }

    /**
     * 应用上传卸载/安装日志
     *
     * @author dongtianhao
     */
    public static class UpLoadService extends IntentService {
        private static final String NAME = "UpLoadService";

        /**
         * 一定要有无参构造，方便系统来实例化IntentService,名字自己指定,但是必须唯一
         */
        public UpLoadService() {
            super(NAME);
        }

        @Override
        protected void onHandleIntent(Intent intent) {
            String pkgName = intent.getStringExtra(ACTION_PKGNAME);
            String type = intent.getStringExtra(Constant.TYPE);
            LogUtil.trace(Log.ERROR, TAG, pkgName);
            // 上传
            upload(type, pkgName);

        }

        /**
         * 上报安装信息
         *
         * @param packageName
         */
        private void upload(final String type, final String packageName) {
            AppModel appInfoByPkg = Util.getAppInfoFromDB(packageName);
            if (appInfoByPkg != null) {
                String json = GsonUtil.toUploadJson(type, packageName, appInfoByPkg.getLocalVersionCode() == 0
                        ? appInfoByPkg.getRemoteVersionCode() : appInfoByPkg.getLocalVersionCode());
                HttpUtil.post(json, new StringCallback() {
                    @Override
                    public void onResponse(boolean arg0, String arg1, Request arg2, Response arg3) {
                        JsonDataRestult<Object> result = GsonUtil.decode(arg1, new TypeToken<JsonDataRestult<Object>>() {
                        }.getType());
                        if (URLConstants.RetCode.SUCCESS.equals(result.getRetCode())) {
                            LogUtil.trace(Log.DEBUG, TAG, "upload ok");
                        } else {
                            // ToastShow.shortMessage(result.getRetMsg());
                        }
                    }
                });
            }
        }
    }

}